<?php
namespace App\Models\Goods;

use App\Contracts\Repositories\GoodsRepository as GoodsRepositoryContract;

class GoodsRepository implements GoodsRepositoryContract
{
    /**
     * @param $data
     * @return bool
     */
    public function create($data)
    {
        DB::beginTransaction();
        try {
            $goods = json_decode($data['goods'], true);
            $goods['created_at'] = date('Y-m-d H:i:s');
            $goods['updated_at'] = date('Y-m-d H:i:s');
            $goods_id = Goods::insertGetId($goods);
            if (isset($data['goods_record'])) {
                $records = json_decode($data['goods_record'], true);
                foreach ($records as $index => $datum) {
                    $records[$index]['goods_id'] = $goods_id;
                }
                GoodsRecord::insert($records);
            }
            DB::commit();
            return $this->findByConditions(array('id' => $goods_id), array('goodsType', 'goodsRecord'));
        } catch (\Exception $e) {
            DB::rollback();
            Log::info($e->getMessage());
            return null;
        }
    }

    public function modify($goods, $conditions)
    {
        return Goods::where($conditions)->update($goods);
    }

    public function delete($conditions, $softDeletion)
    {
        if ($softDeletion == true) {
            return Goods::where($conditions)->update(array('deleted_at' => date('Y-m-d H:i:s')));
        } else {
            return Goods::where($conditions)->delete();
        }
    }

    public function findByType($typeId)
    {
        return Goods::with('prizeType', 'sponsor')->where('type_code', $typeId)->get()->toArray();
    }

    public function findByConditions($conditions, $withs)
    {
        if (is_array($withs) || is_string($withs) || is_null($withs)) {
            return Goods::with($withs)->where($conditions)->get()->toArray();
        } else {
            return null;
        }
    }
}
